<?php

namespace common\models\site;

use Yii;
use common\helpers\Url;

/**
 * This is the model class for table "{{%site_map}}".
 *
 * @property int $id
 * @property string $name
 * @property int $type
 * @property string $route
 * @property string $scheme
 * @property string $params
 * @property string $mark
 * @property int $status
 * @property int $created_at
 * @property int $updated_at
 */
class SiteMap extends \common\db\ActiveRecord {

    const SCHEME_NATIVE = '';
    const SCHEME_DEFAULT = 'Default';

    /**
     * {@inheritdoc}
     */
    public static function tableName() {
        return '{{%site_map}}';
    }

    /**
     * {@inheritdoc}
     */
    public function rules() {
        return [
            [['name'], 'required'],
            [['type', 'status', 'created_at', 'updated_at'], 'integer'],
            [['name', 'route', 'params', 'mark'], 'string', 'max' => 255],
            [['scheme'], 'string', 'max' => 50],
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function attributeLabels() {
        return [
            'id' => 'ID',
            'name' => 'Name',
            'type' => 'Type',
            'route' => 'Route',
            'scheme' => 'Scheme',
            'params' => 'Params',
            'mark' => 'Mark',
            'status' => 'Status',
            'created_at' => 'Created At',
            'updated_at' => 'Updated At',
        ];
    }

    public function getSchemeText() {
        if ($this->type == 0) {
            return static::SCHEME_NATIVE;
        }
        return $this->scheme ?: static::SCHEME_DEFAULT;
    }

    public function getFormatParams() {
        return $this->params ? unserialize($this->params) : null;
    }

    public function getBindParams() {
        return $this->getFormatParams();
    }

    public function getUrl() {
        $url = Yii::t('message', $this->route, $this->getFormatParams());
        if ($this->type == 301) {
            return Url::h5($url);
        }
        return $url;
    }

    public function fields() {
        return [
            'title' => 'name',
            'scheme' => 'schemeText',
            'route' => 'url',
            'data' => 'bindParams',
        ];
    }

}
